package com.adcc.ags.cgw.configuration;

import com.adcc.ags.cgw.App;
import com.adcc.ags.cgw.entity.user.BlackListUser;
import com.adcc.ags.cgw.entity.user.SpecLabel;
import com.adcc.ags.cgw.utils.Constant;
import com.adcc.ags.cgw.utils.FileUtil;
import com.adcc.utility.log.Log;
import com.adcc.utility.xml.*;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;

import java.io.File;
import java.util.List;

/**
 * 黑名单用户列表配置工厂
 */
public class BlackListFactory {

    // 单例
    private static BlackListFactory instance;

    // 用户配置列表
    private List<BlackListUser> invalidUsersList = Lists.newArrayList();

    /**
     * 构造函数
     */
    private BlackListFactory(){

    }

    /**
     * 单例方法
     * @return
     */
    public synchronized static BlackListFactory getInstance(){
        if(instance == null){
            instance = new BlackListFactory();
        }
        return instance;
    }

    public List<BlackListUser> getBlackUsersList() {
        return invalidUsersList;
    }

    /**
     * 读取黑名单
     * @throws Exception
     */
    public void load() throws Exception{
        try {

            // 配置文件存在则加载配置
            String strBlackListFile = App.confPath + File.separator + Constant.STRING_BLACKLIST_FILE;
            if (FileUtil.isExist(strBlackListFile)) {
                ADCCXML adccxml = ADCCXMLFactory.getInstance().createADCCXML();
                adccxml.parseXMLFile(strBlackListFile);
                invalidUsersList = parseBlackList(adccxml, false);
            }
        } catch (Exception ex) {
            Log.error(BlackListFactory.class.getName(), "load() error", ex);
            throw ex;
        }
    }

    /**
     * 解析黑名单列表，如果backup为false，则解析出的黑名单全部为主用BlackListUser，否则全部为备用BlackListUser
     * @param adccxml
     * @throws Exception
     */
    public List<BlackListUser> parseBlackList(ADCCXML adccxml, boolean backup)throws Exception {
        try {
            List<BlackListUser> blackListUserList = Lists.newArrayList();
            SuperNode userNode = adccxml.getSuperNode("blackList");
            if(userNode == null){
                throw new NullPointerException("parse xml error reason:lose <blackList></blackList>");
            }
            for(Node node : userNode.getNodeList()) {
                if(node.getAttributes().containsKey("id") && node.getAttributes().containsKey("name")) {
                    String strID = node.getAttributes().get("id").trim();
                    String strName = node.getAttributes().get("name").trim();
                    BlackListUser blackListUser = new BlackListUser(strID,strName);
                    blackListUser.setBackup(backup);
                    if(node.getUnitList().size() > 0) {
                        for(Unit unit : node.getUnitList()) {
                            if("SendAddress".equals(unit.getAttributes().get("name").trim())){
                                blackListUser.setSendAddress(unit.getText().trim());
                            }
                            if("RecvAddress".equals(unit.getAttributes().get("name").trim())){
                                String srtRecvAddress = unit.getText().trim();
                                if(!Strings.isNullOrEmpty(srtRecvAddress)){
                                    blackListUser.setRecvAddress(srtRecvAddress.split(","));
                                }
                            }
                            if("SMI".equals(unit.getAttributes().get("name").trim())){
                                String strSMI = unit.getText().trim();
                                if(!Strings.isNullOrEmpty(strSMI)){
                                    blackListUser.setSmi(strSMI.split(","));
                                }
                            }
                            if("AN".equals(unit.getAttributes().get("name").trim())){
                                String strAN = unit.getText().trim();
                                if(!Strings.isNullOrEmpty(strAN)){
                                    blackListUser.setAn(strAN.split(","));
                                }
                            }
                            if("SpecLabel".equals(unit.getAttributes().get("name").trim())){
                                SpecLabel specLabel = new SpecLabel();
                                specLabel.setContent(unit.getText().trim());
                                try {
                                    String strIndex = unit.getAttributes().get("index").trim();
                                    if(!Strings.isNullOrEmpty(strIndex)) {
                                        specLabel.setIndex(Integer.parseInt(strIndex));
                                    }
                                } catch (Exception e) {
                                    Log.error(BlackListFactory.class.getName(), "parse xml error reason: invalid speclabel index");
                                }
                                blackListUser.setSpecLabel(specLabel);
                            }
                        }
                    }
                    blackListUserList.add(blackListUser);
                }
            }
            return blackListUserList;
        } catch (Exception ex) {
            Log.error(BlackListFactory.class.getName(), "parseBlackList() error", ex);
            throw ex;
        }
    }

    /**
     * 保存黑名单
     * @param adccxml
     * @return
     */
    public void save(ADCCXML adccxml) {
        try {
            String strBlackListFile = App.confPath + File.separator + Constant.STRING_BLACKLIST_FILE;
            adccxml.createXMLFile(strBlackListFile, XMLPattern.PRETTY);
        } catch (Exception ex) {
            Log.error(BlackListFactory.class.getName(), "save() error", ex);
        }
    }

    /**
     * 删除黑名单列表中的用户，如果backup为false，则删除全部的主用User，否则删除全部的备用User
     * @param backup
     * @exception java.lang.Exception zyy 2016-12-06 添加
     * */
    public void deleteAllBlackListUser(boolean backup) throws Exception{
        try {
            // 删除已有的User
            if (invalidUsersList.size() > 0) {
                List<BlackListUser> tempList = Lists.newArrayListWithExpectedSize(invalidUsersList.size());
                for (BlackListUser blackListUser : invalidUsersList) {
                    if (blackListUser.isBackup() == backup) {
                        tempList.add(blackListUser);
                    }
                }
                invalidUsersList.removeAll(tempList);
            }
        } catch (Exception ex) {
            Log.error(UserListFactory.class.getName(), "deleteAllBlackListUser() error", ex);
            throw ex;
        }
    }

    /**
     * 更新黑名单列表中的用户，如果backup为false，则更新主用BlackListUser，否则更新备用BlackListUser
     * @param adccxml
     * @param backup
     * java.lang.Exception zyy 2016-12-06 添加
     * */
    public void updateBlackUserList(ADCCXML adccxml, boolean backup) throws Exception{
        try {
            // 删除已有的黑名单用户
            deleteAllBlackListUser(backup);

            // 解析黑名单用户列表，添加新的黑名单用户
            invalidUsersList.addAll(parseBlackList(adccxml, backup));
        } catch (Exception ex) {
            Log.error(BlackListFactory.class.getName(), "updateBlackUserList() error", ex);
            throw ex;
        }
    }
}
